package com.sinosoft.brokerchannel.base.utile;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.sinosoft.brokerchannel.base.bins.Channel;
import com.sinosoft.brokerchannel.base.bins.TGatewayChannelInfo;
import com.sinosoft.brokerchannel.base.common.ChannelConstants;
import com.sinosoft.brokerchannel.base.server.ChannelInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 需求名称：[大童理赔渠道平台]<br/>
 * 类描述:[一句话描述该类的功能]<br/>
 *
 * @author shilk
 * @version V1.0
 * @date 2018-8-17 15:08
 */
@Component
public class BusinessUtils {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ChannelInfoService channelInfoService;

    private static final XmlMapper xmlMapper = new XmlMapper();
    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 请求数据（requestBody)进行解密处理，渠道信息验证、服务授权。
     *
     * @param request
     * @throws BusinessException
     */
    public String decryp(HttpServletRequest request) throws BusinessException, IOException {
        String requestBody;
        //获取渠道代码
        String channelCode = request.getParameter("comid");
        if (ToolUtils.isNullOrEmpty(channelCode)) {
            throw new BusinessException(ChannelConstants.ExceptionResult.NOTNULLCOMIDERROR.getCode(),
                                            ChannelConstants.ExceptionResult.NOTNULLCOMIDERROR.getMessage());
        }

        //获取秘钥
        String key = "";
        //获取请求数据
        requestBody = ToolUtils.getReqData(request);

        //获取渠道信息，再获得秘钥
       TGatewayChannelInfo channelInfo= channelInfoService.getChannelInfo(channelCode);
        if (channelInfo != null) {
            request.setAttribute("key", key);
            key = channelInfo.getChannelKey();
        } else {
            throw new BusinessException("", "没有获取到渠道信息，请检查comid是否正确！");
        }
        //根据获得的秘钥解密请求数据（requestbody）
        try {
            requestBody = AESUtil.decrypt(requestBody, key);
            logger.info("外部渠道请求数据：");
            requestBody = requestBody.replaceAll("\\uFEFF", "").replaceAll("GBK|gbk", "UTF-8").trim();
            logger.info(requestBody);
        } catch (Exception e) {
            logger.info(ChannelConstants.ExceptionResult.AESERROR.getCode(), ChannelConstants.ExceptionResult.AESERROR.getMessage());
            throw new BusinessException(ChannelConstants.ExceptionResult.AESERROR.getCode(), ChannelConstants.ExceptionResult.AESERROR.getMessage());
        }
        request.setAttribute("key", key);
        //获得渠道交易代码
        String contentType = request.getContentType().contains("json") ? "json" : "xml";
        Channel channel = this.getChannelTradeCode(requestBody, contentType);
        //将解密后的数据及controller转发路径重新放入request
        request.setAttribute("channelCode", channelCode);
        request.setAttribute("channelTradeCode", channel.getChannelTradeCode());
        request.setAttribute("encryption", true);
        request.setAttribute("requestDispatcherPath", this.getRequestDispatcherPath(channel.getChannelTradeCode()));
        return requestBody;
    }

    /**
     * @param requestBody
     * @return 渠道信息
     * @需求名称：controller服务类
     * @描述:获取请求报文里的渠道信息
     */
    private Channel getChannelTradeCode(String requestBody, String contentType) throws BusinessException, IOException {
        Channel channel = null;
        String tempStr = null;
        if ("xml".equals(contentType)) {
            if (requestBody.contains("Channel")) {
                tempStr = requestBody.substring(requestBody.indexOf("<Channel>"), requestBody.indexOf("</Channel>") + "</Channel>".length()).trim();
                channel = xmlMapper.readValue(tempStr, Channel.class);
            } else {
                throw new BusinessException(ChannelConstants.ExceptionResult.CHANNELNOTNULL.getCode(),
                        ChannelConstants.ExceptionResult.CHANNELNOTNULL.getMessage());
            }
        } else if ("json".equals(contentType)) {
            if (requestBody.contains("Channel")) {
                tempStr = requestBody.substring(requestBody.indexOf("\"Channel\"") - 1);
                tempStr = tempStr.substring(tempStr.indexOf(":") + 1, tempStr.indexOf("}") + 1).trim();
                channel = objectMapper.readValue(tempStr, Channel.class);
            } else {
                throw new BusinessException(ChannelConstants.ExceptionResult.CHANNELNOTNULL.getCode(),
                        ChannelConstants.ExceptionResult.CHANNELNOTNULL.getMessage());
            }
        }
        if (channel == null) {
            throw new BusinessException(ChannelConstants.ExceptionResult.CHANNELNOTNULL.getCode(),
                    ChannelConstants.ExceptionResult.CHANNELNOTNULL.getMessage());
        }
        return channel;
    }

    /**
     * @param channelTradeCode 渠道交易代码
     * @return controller调度路径
     * 需求名称：controller服务类
     * 描述:获取controller的调度路径
     */
    private String getRequestDispatcherPath(String channelTradeCode) {
        switch (channelTradeCode) {
            case "000001":
                return "modelquery";
            case "000002":
                return "premum/quoteprice";
            case "000003":
                return "proposal/proposalgenerate";
            case "000004":
                return "policygenerate";
            case "000005":
                return "carBusinessDetailInfoQuery";
            case "000006":
                return "uploadidentity";
            case "000007":
                return "image/imagecloudstorage";
            case "000008":
                return "coverageStopCalculatePrice";
            case "000009":
                return "coverageStopEndorsementGenerate";
            case "000010":
                return "coverageStopRiskDownload";
            case "000011":
                return "coverageStopApplication";
            case "000012":
                return "coverageStopResumeConfirm";
            case "000013":
                return "certificateIdentificationSystem";
            case "000014":
                return "coverageStopResumArrivalConfirmation";
            case "000015":
                return "vehicleInformationQuery";
            case "000016":
                return "caractualvalue/actualvaluecalculation";
            case "000017":
                return "modelAndPureRiskPremiumInquiry";
            case "000018":
                return "policyRenewalInformationQuery";
            case "000019":
                return "policyRelatedInformationQuery";
            case "000020":
                return "policyApplicationDelete";
            case "000021":
                return "policyApplicationListQuery";
            case "000022":
                return "policyListQuery";
            case "000023":
                return "insuredApplicationTransferPolicy";
            case "000025":
                return "vehicleInformationQueryByFrameNo";
            case "000026":
                return "jyCarModelQueryByVehicleId";
            case "000027":
                return "salesPerformanceQuery";
            case "000028":
                return "drawPrize";
            case "000029":
                return "receiveprize";
            case "000031":
                return "newPlate";
            case "000032":
                return "floatingNotificationPrintList";
            case "000033":
                return "policyNoDetailInfoQuery";
            case "000035":
                return "underwritingRollback";
            case "000036":
                return "collectIdentifyingCode";
            case "000037":
                return "queryForReport";
            case "000038":
                return "copyReport";
            case "000039":
                return "bhRenewal";
            case "000040":
                return "gainFixSpecInfo";
            case "000041":
                return "policylist";
            case "000042":
                return "jsfloatingNotificationPrintList";
            case "000043":
                return "greenTravel";
            case "000044":
                return "downloadUrl";
            case "000045":
                return "plyImageAuthenticate";//渠道影像认证
            case "000049":
                return "plateNoQuery";//车牌号查询
            case "000050":
                return "saveDistribution";//保存配送信息
            case "000051":
                return "qryUnderwrittenList";//保存配送信息
            case "000052":
                return "carPolicyListQuery";//保单列表
            case "000055":
                return "testCodeQuery";//获得验车码
            case "000080":
                return "query/selectChannel";//获得渠道协议
            case "000081":
                return "person/LedgerSend";//台账数据传输
            case "000082":
                return "query/selectOrg";//获得机构信息查询
            case "000083":
                return "person/messaging";//短信
            case "000084":
                return "person/selectLogistics";//获得物流信息查询
            case "000085":
                return "person/withdrawDeposit";//提现接口
            case "000086":
                return "person/selectGpSettletFee";//佣金接口查询
            case "000087":
                return "person/selectGuAccount";//台账接口查询
            case "000088":
                return "ius/selectLogin";//账号登陆
            case "000089":
                return "pay/selectPay";//支付接口
            case "000090":
                return "person/selectBringOutTheDetails";//提现明细查询
            case "000091":
                return "person/selectAchievement";//业绩查询
            case "000092":
                return "recursion/selectRecursionOrg";//推送
            case "000093":
                return "salesReturn/selectEcho";//推送;//
            case "000094":
                return "premum/selectInsurer";//
            case "000095":
                return "";//
            default:
                return "/";
        }
    }
}
